<!-- 工厂选择器组件 -->
<div class="factory-selector">
    <div class="btn-group">
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <i class="fa fa-building"></i>
            <span class="current-factory-name">选择工厂</span>
            <span class="caret"></span>
        </button>
        <ul class="dropdown-menu factory-list">
            <li><a href="javascript:void(0);" class="factory-switch-btn" data-factory-id="0">全部工厂</a></li>
            <li role="separator" class="divider"></li>
            <!-- 工厂列表将通过JavaScript动态加载 -->
        </ul>
    </div>
</div>

<style>
.factory-selector {
    display: inline-block;
    margin-right: 10px;
}

.factory-selector .btn {
    min-width: 120px;
    text-align: left;
}

.factory-selector .current-factory-name {
    margin: 0 5px;
}

.factory-selector .factory-list {
    max-height: 300px;
    overflow-y: auto;
}

.factory-selector .factory-item {
    padding: 8px 15px;
    border-bottom: 1px solid #eee;
}

.factory-selector .factory-item:last-child {
    border-bottom: none;
}

.factory-selector .factory-item:hover {
    background-color: #f5f5f5;
}

.factory-selector .factory-item.active {
    background-color: #337ab7;
    color: white;
}

.factory-selector .factory-item.active:hover {
    background-color: #286090;
}
</style>

<script>
$(function() {
    // 初始化工厂选择器
    initFactorySelector();
    
    // 工厂切换事件
    $(document).on('click', '.factory-switch-btn', function() {
        var factoryId = $(this).data('factory-id');
        var factoryName = $(this).text();
        
        if (factoryId == 0) {
            // 切换为全部工厂
            switchFactory(0, '全部工厂');
        } else {
            // 切换为指定工厂
            switchFactory(factoryId, factoryName);
        }
    });
    
    function initFactorySelector() {
        // 获取用户可访问的工厂列表
        Fast.api.ajax({
            url: 'scanwork/factory_switch/getList',
            data: {}
        }, function(data, ret) {
            var factoryList = $('.factory-list');
            var currentFactoryId = getCurrentFactoryId();
            
            // 清空现有列表（保留"全部工厂"选项）
            factoryList.find('.factory-item').remove();
            
            // 添加工厂选项
            if (data && data.length > 0) {
                data.forEach(function(factory) {
                    var isActive = factory.id == currentFactoryId ? 'active' : '';
                    var item = '<li class="factory-item ' + isActive + '">' +
                        '<a href="javascript:void(0);" class="factory-switch-btn" data-factory-id="' + factory.id + '">' +
                        factory.name + ' (' + factory.code + ')' +
                        '</a></li>';
                    factoryList.append(item);
                });
            }
            
            // 更新当前工厂名称显示
            updateCurrentFactoryName(currentFactoryId, data);
        });
    }
    
    function switchFactory(factoryId, factoryName) {
        if (factoryId == 0) {
            // 全部工厂模式
            sessionStorage.removeItem('current_factory_id');
            updateCurrentFactoryName(0, null);
            updateFactoryItems(0);
        } else {
            // 指定工厂模式
            Fast.api.ajax({
                url: 'scanwork/factory_switch/switch',
                data: {factory_id: factoryId}
            }, function(data, ret) {
                sessionStorage.setItem('current_factory_id', factoryId);
                updateCurrentFactoryName(factoryId, null);
                updateFactoryItems(factoryId);
                Toastr.success('工厂切换成功');
                
                // 触发工厂切换事件
                $(document).trigger('factoryChanged', [factoryId, factoryName]);
            });
        }
    }
    
    function updateCurrentFactoryName(factoryId, factoryList) {
        var nameElement = $('.current-factory-name');
        
        if (factoryId == 0) {
            nameElement.text('全部工厂');
        } else if (factoryList) {
            var factory = factoryList.find(function(f) { return f.id == factoryId; });
            if (factory) {
                nameElement.text(factory.name);
            }
        } else {
            // 从当前选中的项目获取名称
            var selectedItem = $('.factory-item.active .factory-switch-btn');
            if (selectedItem.length > 0) {
                nameElement.text(selectedItem.text());
            }
        }
    }
    
    function updateFactoryItems(activeFactoryId) {
        $('.factory-item').removeClass('active');
        $('.factory-switch-btn').each(function() {
            if ($(this).data('factory-id') == activeFactoryId) {
                $(this).closest('.factory-item').addClass('active');
            }
        });
    }
    
    function getCurrentFactoryId() {
        return sessionStorage.getItem('current_factory_id') || 0;
    }
    
    // 页面加载时恢复工厂选择状态
    var savedFactoryId = getCurrentFactoryId();
    if (savedFactoryId != 0) {
        updateFactoryItems(savedFactoryId);
    }
});
</script>
